package com.heima.wemedia.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.constants.KafkaMessageConstants;
import com.heima.model.wemedia.dto.WmNewsDto;
import com.heima.model.wemedia.dto.WmNewsPageReqDto;
import com.heima.model.wemedia.entity.WmNews;
import com.heima.model.wemedia.entity.WmUser;
import com.heima.utils.common.WmThreadLocalUtil;
import com.heima.wemedia.dao.*;
import com.heima.wemedia.service.WmNewsService;
import org.apache.commons.beanutils.BeanMap;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 自媒体文章表(WmNews)表服务实现类
 *
 * @author makejava
 * @since 2022-04-12 16:28:56
 */
@Service("wmNewsService")
public class WmNewsServiceImpl implements WmNewsService {
    @Resource
    private WmNewsDao wmNewsDao;
    
    @Resource
    private WmUserDao wmUserDao;

    @Resource
    private WmChannelDao wmChannelDao;

    @Resource
    private WmNewsMaterialDao wmNewsMaterialDao;

    @Resource
    private WmMaterialDao wmMaterialDao;

    @Resource
    private KafkaTemplate kafkaTemplate;

    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    @Override
    public WmNews queryById(Long id) {
        return this.wmNewsDao.queryById(id);
    }


    /**
     * 新增数据
     *
     * @param wmNews 实例对象
     * @return 实例对象
     */
    @Override
    public WmNews insert(WmNews wmNews) {
        this.wmNewsDao.insert(wmNews);
        return wmNews;
    }

    /**
     * 修改数据
     *
     * @param wmNews 实例对象
     * @return 实例对象
     */
    @Override
    public WmNews update(WmNews wmNews) {
        this.wmNewsDao.update(wmNews);
        return this.queryById(wmNews.getId());
    }

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(Long id) {
        return this.wmNewsDao.deleteById(id) > 0;
    }

    @Override
    public ResponseResult submit(WmNewsDto dto) {
        WmNews wmNews =new WmNews();
        BeanUtils.copyProperties(dto,wmNews);
        System.out.println(wmNews);
        //内容图片
        List<Map> list= JSON.parseArray(dto.getContent(), Map.class);
        List<String> contentImages = list.stream().filter(map -> "image".equals(map.get("type"))).map(map -> map.get("value").toString()).collect(Collectors.toList());
        //如果是自动就将内容图片给到封面
        if (dto.getType()==-1){
            if (contentImages.size()<=0){
                wmNews.setType(0);
                dto.setImages(new ArrayList<>());
            }
            if (contentImages.size()<3){
                wmNews.setType(1);
                dto.setImages(contentImages.stream().limit(1).collect(Collectors.toList()));
            }
            if (contentImages.size() >=3){
                wmNews.setType(3);
                dto.setImages(contentImages.stream().limit(3).collect(Collectors.toList()));
            }
        }
        //判断是否有封面图片
        if (wmNews.getType()>0){
            wmNews.setImages(StringUtils.join(dto.getImages(),","));
        }
        //填充文章数据
        saveWmNews(wmNews);
        //填充图片关系表
        saveWmNewsMaterial(wmNews,contentImages,1);
        saveWmNewsMaterial(wmNews, dto.getImages(), 0);
        //发送消息通知审核服务进行文章审核 , 状态为 1 : 提交（待审核） 才需要审核
        if (wmNews.getStatus() == 1) {
            kafkaTemplate.send(KafkaMessageConstants.WM_NEWS_AUTO_SCAN_TOPIC, wmNews.getId().toString());
        }
        return ResponseResult.okResult(wmNews);
    }

    @Override
    public ResponseResult getList(WmNewsPageReqDto dto) {
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        dto.checkParam();
        Map<String, Object> queryParam = BeanUtil.beanToMap(dto);
        queryParam.put("userId", WmThreadLocalUtil.getUser().getId());
        PageHelper.startPage(dto.getPage(), dto.getSize());
        Page<WmNews> page = wmNewsDao.queryByMap(queryParam);

        //4. 封装数据返回
        ResponseResult result = new PageResponseResult(dto.getPage(), dto.getSize(), (int) page.getTotal());
        result.setData(page.getResult());
        return result;
    }

    @Override
    public ResponseResult delete(Long newsId) {
        WmNews wmNews = wmNewsDao.queryById(newsId);

        if (wmNews == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }

        wmNewsDao.deleteById(newsId);
        wmNewsMaterialDao.deleteByNewsId(wmNews.getId());
        return ResponseResult.okResult("删除成功");
    }

    private void saveWmNewsMaterial(WmNews wmNews, List<String> images,Integer type) {
        if (images==null||images.size() == 0){
            return;
        }
        List<Long> ids=wmMaterialDao.queryIdsByUrls(images);
        if(ids.size()< images.size()){
            throw new RuntimeException("素材数据丢失!");
        }
        wmNewsMaterialDao.saveImageRelation(wmNews.getId(),ids,type);

    }

    private void saveWmNews(WmNews wmNews) {
        WmUser wmUser = wmUserDao.queryById(WmThreadLocalUtil.getUser().getId());
        wmNews.setUpdatedBy(wmUser.getId());
        wmNews.setUserId(wmUser.getId().longValue());
        wmNews.setUpdatedTime(new Date());
        wmNews.setStatus(1);
        wmNews.setEnable(0);
        System.out.println(wmNews);

        //新增
        if (wmNews.getId() == null) {
            wmNews.setCreatedTime(new Date());
            wmNews.setCreatedBy(wmUser.getId().toString());
            wmNewsDao.insert(wmNews);
            return;
        }

        //修改
        wmNewsDao.update(wmNews);

        //删除素材和文章的引用关系
        wmNewsMaterialDao.deleteByNewsId(wmNews.getId());
    }

}
